package service

import (
	"context"
	"fmt"
	"github.com/robfig/cron/v3"
	"time"
	"user-service/basic/config"
	__ "user-service/basic/proto"
	"user-service/handler/model"
)

func (s *Server) CreateReserveStock(_ context.Context, in *__.CreateReserveStockReq) (*__.CreateReserveStockResp, error) {
	stock := model.ReserveStock{
		Username:       in.Username,
		IdCard:         in.IdCard,
		Phone:          in.Phone,
		HospitalId:     in.HospitalId,
		PackageId:      in.PackageId,
		ReserveDate:    in.ReserveDate,
		TotalStock:     in.TotalStock,
		UsdStock:       in.UsdStock,
		RemainingStock: in.RemainingStock,
	}
	//人员信息格式是否合法
	if in.Username == "" {
		return nil, fmt.Errorf("用户名不能等于空")
	}
	//校验库存是否充足
	if stock.TotalStock == 0 {
		return nil, fmt.Errorf("库存不充足")
	}

	config.DB.Create(&stock)

	return &__.CreateReserveStockResp{
		ReserveStock: int64(stock.ID),
	}, nil
}
func (s *Server) ReserveStockList(_ context.Context, in *__.ReserveStockListReq) (*__.ReserveStockListResp, error) {
	var res model.ReserveStock
	c := cron.New()
	go func() {
		time.Sleep(time.Second * 10)
		res.Create30DayReserveStock(config.DB)
	}()
	c.Start()

	var reserveStock []model.ReserveStock

	config.DB.Find(&reserveStock)
	var reserveStocklists []*__.ReserveStockList
	for _, m := range reserveStock {
		list := __.ReserveStockList{
			Username:       m.Username,
			IdCard:         m.IdCard,
			Phone:          m.Phone,
			HospitalId:     m.HospitalId,
			PackageId:      m.PackageId,
			ReserveDate:    m.ReserveDate,
			TotalStock:     m.TotalStock,
			UsdStock:       m.UsdStock,
			RemainingStock: m.RemainingStock,
		}
		reserveStocklists = append(reserveStocklists, &list)
	}
	return &__.ReserveStockListResp{
		List: reserveStocklists,
	}, nil
}
